<template>
    <div class="container">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h1 style="margin: 0;">班级管理：{{ classroomName }}</h1>
            <div>
                <el-button type="success" @click="openChat" style="margin-right: 10px;">打开班级群聊</el-button>
                <el-button 
                    :type="isConnected ? 'warning' : 'danger'" 
                    @click="toggleConnection" 
                    style="margin-right: 10px;">
                    <span>{{ isConnected ? '断开实时连接' : '连接实时消息' }}</span>
                </el-button>
                <el-button disabled style="margin-right: 10px;">
                    <div style="display: flex; align-items: center;">
                        <span>实时消息状态: </span>
                        <div class="status-indicator" :class="{ 'connected': isConnected }" style="margin-left: 5px;"></div>
                        <span style="margin-left: 5px;">{{ isConnected ? '已连接' : '未连接' }}</span>
                    </div>
                </el-button>
                <el-button type="success" @click="goBack">返回</el-button>
            </div>
        </div>
        <h3>1、每周课程表编辑：</h3>
        <WeeksTable :classroomId="classroomId" :classroomName="classroomName" />
        <h3>2、班级课程管理：</h3>
        <CourseTable :classroomId="classroomId" />
        <h3>3、班级学员管理：</h3>
        <StudentTable :classroomId="classroomId" />
        
        <ChatDrawer ref="chatDrawer" :classroomId="classroomId" />
    </div>
</template>

<script setup>
import { reactive, ref, onMounted, onUnmounted, watch } from "vue";
import WeeksTable from "@/components/table/WeeksTable.vue";
import CourseTable from "@/components/table/CourseTable.vue";
import StudentTable from "@/components/table/StudentTable.vue";
import ChatDrawer from "@/components/drawer/ChatDrawer.vue";
import router from "@/router";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { 
    initChatWebSocket, 
    disconnectChatWebSocket, 
    getChatConnectionStatus 
} from "@/apis/chat";

function goBack() {
    router.go(-1);
}

// Chat drawer reference
const chatDrawer = ref(null);

// Function to open chat drawer
function openChat() {
    chatDrawer.value.open();
}

// WebSocket connection state
const isConnected = ref(false);

// 监控WebSocket状态变化（每秒检查一次）
let statusCheckInterval = null;

// 开始监控连接状态
function startStatusMonitoring() {
    if (statusCheckInterval) return;
    
    // 每秒检查一次连接状态
    statusCheckInterval = setInterval(() => {
        const status = getChatConnectionStatus();
        if (isConnected.value !== status.connected) {
            isConnected.value = status.connected;
        }
    }, 1000);
}

// 停止监控连接状态
function stopStatusMonitoring() {
    if (statusCheckInterval) {
        clearInterval(statusCheckInterval);
        statusCheckInterval = null;
    }
}

// Toggle WebSocket connection
function toggleConnection() {
    if (isConnected.value) {
        // 当前已连接，执行断开操作
        disconnectChat();
    } else {
        // 当前未连接，执行连接操作
        connectChat();
    }
}

// 连接WebSocket
function connectChat() {
    try {
        // 开始监控状态变化
        startStatusMonitoring();
        
        // 初始化WebSocket连接
        const initResult = initChatWebSocket();
        
        if (!initResult) {
            ElMessage.error('无法初始化WebSocket连接');
            return;
        }
        
        // 立即检查一次连接状态
        const status = getChatConnectionStatus();
        isConnected.value = status.connected;
        
        if (status.connected) {
            ElMessage.success('实时连接已建立');
        } else {
            // 如果没有立即连接成功，设置一个延迟检查
            setTimeout(() => {
                const delayedStatus = getChatConnectionStatus();
                isConnected.value = delayedStatus.connected;
                
                if (delayedStatus.connected) {
                    ElMessage.success('实时连接已建立');
                }
            }, 500);
        }
    } catch (error) {
        console.error('连接WebSocket失败:', error);
        ElMessage.error('连接失败，请重试');
        isConnected.value = false;
    }
}

// 断开WebSocket连接
function disconnectChat() {
    try {
        // 断开连接
        const disconnectResult = disconnectChatWebSocket();
        
        // 立即更新状态
        isConnected.value = false;
        
        if (disconnectResult) {
            ElMessage.success('已断开实时连接');
        } else {
            ElMessage.info('连接已断开');
        }
        
        // 停止监控状态变化
        stopStatusMonitoring();
    } catch (error) {
        console.error('断开连接失败:', error);
        ElMessage.error('断开连接失败');
        
        // 再次检查状态
        const status = getChatConnectionStatus();
        isConnected.value = status.connected;
    }
}

// 组件加载时启动状态监控
onMounted(() => {
    // 检查初始连接状态
    const status = getChatConnectionStatus();
    isConnected.value = status.connected;
    
    // 开始定期监控状态
    startStatusMonitoring();
});

// 组件卸载时清理
onUnmounted(() => {
    // 停止状态监控
    stopStatusMonitoring();
    
    // 断开连接（如果已连接）
    if (isConnected.value) {
        disconnectChat();
    }
});

const classroomDetail = reactive({});
const route = useRoute();
const classroomId = route.query.classroomId;
const classroomName = decodeURIComponent(route.query.classroomName);
</script>

<style scoped>
.status-indicator {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background-color: #ff4949;
    display: inline-block;
    transition: background-color 0.3s;
}

.status-indicator.connected {
    background-color: #67c23a;
}
</style>